package com.lancoo.answer.view.fragment.listenmatch

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.TranslateAnimation
import androidx.databinding.ObservableArrayList
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentListenMatchChildBinding
import com.lancoo.answer.databinding.EvViewItemOptionBinding
import com.lancoo.answer.helper.recyclerview.BindingViewAdapter
import com.lancoo.answer.helper.recyclerview.BindingViewHolder
import com.lancoo.answer.helper.recyclerview.SingleTypeAdapter
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.ChildOption
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Item
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.util.CustomPictureTextViewUtil
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.combinationView.FillContextAnswerResultView

/**
 * @Description 听力匹配，听力综合，听力排序 查看
 * @Author dadong
 * @Date 05-23-2022 周一 17:55
 */
class ListenParagraphAnalysisFragment : BaseVMFragment<EvFragmentListenMatchChildBinding>(),
    BindingViewAdapter.ItemDecorator {
    private var optionList = ObservableArrayList<EvOptionBean>()
    private lateinit var mAdapter: SingleTypeAdapter<EvOptionBean>
    private var callback: OptionCallback? = null
    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0
    private var itemSortIndex: String = "" //当前选择的序号

    companion object {
        fun loadFragment(typeIndex: Int, queseIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val listenParagraphAnalysisFragment = ListenParagraphAnalysisFragment()
            listenParagraphAnalysisFragment.arguments = mBundle
            return listenParagraphAnalysisFragment
        }
    }

    override fun initView(view: View) {

    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_listen_match_child
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        Log.e("听力排序", "initData $defaultLoadIndex")
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        setOptionList(this.ques.ChildList!![0].ChildOptionList!!)
        if (defaultLoadIndex > 0 && defaultLoadIndex < ques.ChildList!![0].ItemList!!.size) {
            itemSortIndex = this.ques.ChildList!![0].ItemList!![defaultLoadIndex].ItemSortIndex!!
        } else {
            itemSortIndex = this.ques.ChildList!![0].ItemList!![0].ItemSortIndex!!
        }
        mBinding.childStatisticsView.setQues(ques)
        initWvAsk()
        initAdapter()
        updateCheck()
    }

    //选项的adapter
    private fun initAdapter() {
        mAdapter = SingleTypeAdapter(requireContext(), R.layout.ev_view_item_option, optionList)
        mBinding.optionRv.adapter = mAdapter.apply {
            itemDecorator = this@ListenParagraphAnalysisFragment
        }

        mBinding.optionRv.layoutManager = LinearLayoutManager(requireContext())
    }

    private fun initWvAsk() {
        mBinding.tvChildAsk.setDisableInterceptTouch(true)
        mBinding.tvChildAsk.setQues(ques)
        mBinding.tvChildAsk.initWebView(requireActivity(),
            ques.ChildList!![0].ChildAsk!!,
            object : InteractWebView.Callback {
                override fun finishCallback() {
                    wvLoadUrl(itemSortIndex)
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(position)
                    if (getRealItem() != null) {
                        showResultView(getRealItem()!!)
                    }
                }
            })
        if (getRealItem() != null) {
            showResultView(getRealItem()!!)
        }
    }

    //答题点下划线，高亮等等绘制
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.tvChildAsk.scrollPosition(position)
        if (ConstantBean.taskState != TaskState.ORIGINAL) {
            ques.ChildList!![0].ItemList!!.forEach {
                mBinding.tvChildAsk.loadUrl(
                    it,
                    position == it.ItemSortIndex.toString(), false, true
                )
            }
        } else {
            ques.ChildList!![0].ItemList!!.forEach {
                mBinding.tvChildAsk.loadOriginUrl(
                    it,
                    position == it.ItemSortIndex.toString(), true
                )
            }
        }
    }

    private fun updateCheck() {
        resetState()
        ques.ChildList!![0].ItemList!!.forEach { item ->
            optionList.forEach { evOptionBean ->
                if (item.StuAnswer == evOptionBean.OptionIndex) {
                    evOptionBean.SelectState = 2
                }
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    fun setOptionList(optionList: ArrayList<ChildOption>) {
        this.optionList.clear()
        optionList.forEach {
            val option = EvOptionBean().apply {
                Option = it.Option
                OptionIndex = it.OptionIndex
            }
            this.optionList.add(option)
        }
    }

    fun resetState() {
        optionList.forEach { it.SelectState = 0 }
    }


    fun setCallback(callback: OptionCallback) {
        this.callback = callback
    }

    interface OptionCallback {
        fun clickCallback(item: EvOptionBean)
    }

    //获取Item
    fun getRealItem(): Item? {
        ques.ChildList!!.forEach {
            it.ItemList!!.forEachIndexed { index, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    return item
                }
            }
        }
        return null
    }


    fun showResultView(item: Item) {
        if (ConstantBean.taskControlBean!!.trainSence == 1 || ConstantBean.taskControlBean!!.trainSence == 2
            || ConstantBean.taskControlBean!!.trainSence == 3
        ) {
            return
        }
        val fillContextAnswerResultView: FillContextAnswerResultView =
             mBinding.resultView.root.findViewById(R.id.fill_context_answer)
        val typeNo = ques.TypeNo
        fillContextAnswerResultView.setFillResult(item)
         mBinding.resultView.root.findViewById<View>(R.id.ll_close)
            .setOnClickListener { v: View? -> mBinding.resultView.root.visibility = View.GONE }
        if (ConstantBean.taskControlBean!!.expired) {
            fillContextAnswerResultView.showAnalysisAndAnswer()
        }
        if (TextUtils.equals("m", typeNo)) { //匹配题只显示答案解析
            fillContextAnswerResultView.onlyShowAnalysis()
        }
        val ctrlAnimation = TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_SELF, 0f, TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 1f, TranslateAnimation.RELATIVE_TO_SELF, 0f
        )
        ctrlAnimation.duration = 400
        mBinding.resultView.root.visibility = View.VISIBLE
        mBinding.resultView.root.startAnimation(ctrlAnimation)
    }

    fun setCurrentItem(itemIndex: Int) {
        itemSortIndex = this.ques.ChildList!![0].ItemList!![itemIndex].ItemSortIndex!!
        wvLoadUrl(itemSortIndex)
    }

    override fun decorator(
        holder: BindingViewHolder<ViewDataBinding>?,
        position: Int,
        viewType: Int
    ) {
        val itemBinding: EvViewItemOptionBinding = holder!!.binding as EvViewItemOptionBinding
        CustomPictureTextViewUtil(context, itemBinding.tvContent, itemBinding.item!!.Option)
    }

    //获取序号在ItemList 中的位置
    fun getRealIndex(): Int {
        ques.ChildList!![0].ItemList!!.forEachIndexed { index, item ->
            if (item.ItemSortIndex == itemSortIndex) {
                return index
            }
        }
        return 0
    }

    fun adjustFontSize(){
        mBinding.tvChildAsk.setFontSize()
    }
}